﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyBlog.IRepository;
using MyBlog.IService;
using MyBlog.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebServe_demo.Utility;

namespace WebServe_demo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class TypeController : ControllerBase
    {
        private readonly ITypeInfoRepository _iTypeInfoRepository;
      //  private readonly ITypeInfoService _iTypeInfoRepository;
        public TypeController(ITypeInfoRepository iTypeInfoService)
        {
            this._iTypeInfoRepository = iTypeInfoService;
        }
        [HttpGet("Types")]
        public async Task<ApiResult> Types()
        {
            var types = await _iTypeInfoRepository.QueryAsync();
            if (types.Count == 0) return ApiResultHelper.Error("没有更多的类型");
            return ApiResultHelper.Success(types);

        }
        [HttpPost("Create")]
        public async Task<ApiResult> Create(string name )
        {
            #region 数据验证
            if (String.IsNullOrWhiteSpace(name)) return ApiResultHelper.Error("类型名不能为空");
            #endregion
            TypeInfo type = new TypeInfo
            {
                Name = name
            };
            bool b = await _iTypeInfoRepository.CreateAsync(type);
            if (!b) return ApiResultHelper.Error("添加失败");
            return ApiResultHelper.Success(b);
        }
        [HttpPut("Edit")]
        public async Task<ApiResult> Edit(int id,string name )
        {
            var type = await _iTypeInfoRepository.FindAsync(id);
            if (type == null) return ApiResultHelper.Error("没有找到该文章");
            type.Name = name;
          
            bool b = await _iTypeInfoRepository.EditAsync(type);
            if (!b) return ApiResultHelper.Error("修改失败");
            return ApiResultHelper.Success(type);
        }

        [HttpDelete("Delete")]
        public async Task<ApiResult> Delete(int id)
        {
           bool b= await _iTypeInfoRepository.DeleteAsync(id);
            if (!b) return ApiResultHelper.Error("删除失败");
            return ApiResultHelper.Success(b);
        }


    }
}
